﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using APA_DAO;
using TAM_SPORT;
using DAO;

namespace AMS
{
    public partial class FrmEditMembers : Form
    {
        private int invoiceId;
        private int id;
        public FrmEditMembers()
        {
            InitializeComponent();
            this.BackColor = Color.LightCyan;
            init();
        }
        public FrmEditMembers(int id)
        {
            InitializeComponent();
            this.invoiceId = id;
            this.BackColor = Color.LightCyan;
            init();

            dtgCustomer.ColumnHeadersDefaultCellStyle.BackColor = Color.LightSkyBlue;
            dtgCustomer.GridColor = Color.BurlyWood;
            dtgCustomer.EnableHeadersVisualStyles = false;
            this.BackColor = Color.LightCyan;

        }
        private void init()
        {
            dtpDayOfBirth.Format = DateTimePickerFormat.Custom;
            dtpDayOfBirth.CustomFormat = "dd/MM/yyyy";

            dtpIssueDate.Format = DateTimePickerFormat.Custom;
            dtpIssueDate.CustomFormat = "dd/MM/yyyy";
        }
        public void loadGrid(int id)
        {
            KhachThueDao dao = new KhachThueDao();
            DataTable table = dao.getCustomerByInvoiceId(id);
            dtgCustomer.Rows.Clear();
            int i = 0;
            if (table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    i = dtgCustomer.Rows.Add();
                    dtgCustomer.Rows[i].Cells[0].Value = i + 1;
                    dtgCustomer.Rows[i].Cells[1] = row["HINH_ANH"] == null ? null : loadImage(row["HINH_ANH"].ToString());
                    dtgCustomer.Rows[i].Cells[2].Value = row["HO_VA_TEN"].ToString();
                    dtgCustomer.Rows[i].Cells[3].Value = DateTime.Parse(row["NGAY_SINH"].ToString()).ToString("dd/MM/yyyy");
                    dtgCustomer.Rows[i].Cells[4].Value = "M".Equals(row["GIOI_TINH"].ToString())? "Nam": "Nữ";
                    dtgCustomer.Rows[i].Cells[5].Value = "1".Equals(row["LEVEL"].ToString()) ? "Người đại diện" : "Khách thuê cùng";
                    dtgCustomer.Rows[i].Cells[6].Value = row["SO_DT"].ToString();
                    dtgCustomer.Rows[i].Cells[7].Value = row["CMND"].ToString();
                    dtgCustomer.Rows[i].Cells[8].Value = row["NGAY_CAP"]== System.DBNull.Value ? "" : DateTime.Parse(row["NGAY_CAP"].ToString()).ToString("dd/MM/yyyy");
                    dtgCustomer.Rows[i].Cells[9].Value = row["NOI_CAP"].ToString();
                    dtgCustomer.Rows[i].Cells[10].Value = row["DIA_CHI"].ToString();
                    dtgCustomer.Rows[i].Cells[14].Value = row["ID"].ToString();
                    dtgCustomer.Rows[i].Cells[13].Value = row["LEVEL"].ToString();
                }
            }
        }

        private Image resizeImage(Image imgToResize, Size size)
        {
            return (Image)(new Bitmap(imgToResize, size));
        }

        private DataGridViewImageCell loadImage(string url)
        {
            try
            {
                Image image = Image.FromFile(url);
                DataGridViewImageCell imageCell = new DataGridViewImageCell();
                Image imagedis = resizeImage(image, new Size(150, 150));
                imageCell.Value = imagedis;
                image.Dispose();
                return imageCell;
            }
            catch
            {
                return new DataGridViewImageCell();
            }
        }
        private void FrmEditMembers_Load(object sender, EventArgs e)
        {
            loadGrid(this.invoiceId);
        }

        private void dtgCustomer_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                int id = int.Parse(dtgCustomer.Rows[e.RowIndex].Cells[14].Value.ToString());
                int level = int.Parse(dtgCustomer.Rows[e.RowIndex].Cells[13].Value.ToString());
                if (e.ColumnIndex == 1)
                {
                    if (level == 1)
                    {
                        // not yet support, so we don't show anything. because it is bug.
                        Confirm f = new Confirm("Bạn muốn thay đổi người đại diện");
                        f.ShowDialog();
                        if (f.IsAccept)
                        {
                            FrmDoiNguoiDaiDien fr = new FrmDoiNguoiDaiDien(this.invoiceId, id, true);
                            fr.ShowDialog();
                            f.Dispose();
                            loadGrid(this.invoiceId);
                        }
                    }
                    else
                    {
                        
                    }
                }
            }
        }

        private void loadKhachThueInfo(int id)
        {
            KhachThueDao dao = new KhachThueDao();
            DataRow khachThue = dao.getCustomerById(id);
            if (khachThue != null)
            {
                this.id = id;
                this.invoiceId = Int32.Parse(khachThue["SO_THUE_PHONG"].ToString());
                txtFullName.Text = khachThue["HO_VA_TEN"].ToString();
                dtpDayOfBirth.Text = khachThue["NGAY_SINH"].ToString();
                if (khachThue["GIOI_TINH"].ToString() == "M")
                {
                    rdoMale.Checked = true;
                }
                else
                {
                    rdbFemale.Checked = true;
                }
                //txtPhone.Text = khachThue["SO_DT"].ToString() 
                txtPhone.Text = khachThue["SO_DT"] != null ? khachThue["SO_DT"].ToString() : null;
                txtIdCard.Text = khachThue["CMND"] != null ? khachThue["CMND"].ToString() : null;
                dtpIssueDate.Text = khachThue["NGAY_CAP"] != null ? khachThue["NGAY_CAP"].ToString() : null;
                txtIssuePlace.Text = khachThue["NOI_CAP"] != null ? khachThue["NOI_CAP"].ToString() : null;
                txtAdress.Text = khachThue["DIA_CHI"] != null ? khachThue["DIA_CHI"].ToString() : null;
                if (khachThue["HINH_ANH"] != null)
                {
                    loadImageCapture(khachThue["HINH_ANH"].ToString());
                }
            }
            else
            {
                Error err = new Error("Không tìm thấy khách thuê này.");
                err.ShowDialog();
                err.Dispose();
            }
        }

        public void loadImageCapture(string filename)
        {
            string path = filename;
            if (!String.IsNullOrEmpty(path))
            {
                try
                {
                    ptCusImage.LoadAsync(path);
                    ptCusImage.SizeMode = PictureBoxSizeMode.Zoom;
                    ptCusImage.Text = filename;
                }
                catch (Exception ex)
                {
                    ptCusImage.Image = null;
                    Console.WriteLine(ex);
                }
            }
            
        }
        private void dtgCustomer_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                int id = int.Parse(dtgCustomer.Rows[e.RowIndex].Cells[14].Value.ToString());
                // Sửa button
                if (e.ColumnIndex == 11)
                {
                    loadKhachThueInfo(id);
                }
                // Xóa button
                if (e.ColumnIndex == 12)
                {
                    int level = int.Parse(dtgCustomer.Rows[e.RowIndex].Cells[13].Value.ToString());
                    if (level == 1)
                    {
                        KhachThueDao dao = new KhachThueDao();
                        if (dao.getCustomerByInvoiceId(this.invoiceId).Rows.Count > 1)
                        {
                            FrmDoiNguoiDaiDien f = new FrmDoiNguoiDaiDien(this.invoiceId, id, false);
                            f.ShowDialog();
                            //dao.deleteKhachThue(id);
                            loadGrid(this.invoiceId);
                            //f.lblTit
                        }
                        else
                        {
                            // ko the xoa nguoi dai dien
                            Error er = new Error("Không thể xóa người đại diện này.");
                            er.ShowDialog();
                            er.Dispose();
                        }

                    }
                    else
                    {
                        Confirm f = new Confirm("Bạn muốn xóa thông tin khách thuê này?");
                        f.ShowDialog();
                        if (f.IsAccept)
                        {
                            KhachThueDao dao = new KhachThueDao();
                            //MotoDao dao = new MotoDao();
                            if (dao.deleteKhachThue(id))
                            {
                                Result re = new Result("Xóa thành công.");
                                re.ShowDialog();
                                re.Dispose();
                                loadGrid(this.invoiceId);
                            }
                            else
                            {
                                Error er = new Error("Xóa thất bại.");
                                er.ShowDialog();
                                er.Dispose();
                            }
                            f.Dispose();
                        }
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            KhachThueDao dao = new KhachThueDao();
            StringBuilder strErr = new StringBuilder();
            int i = 0;
            bool errflg = false;
            if (string.IsNullOrEmpty(txtFullName.Text))
            {
                i++;
                strErr.Append(i + ". Chưa nhập họ tên.");
                errflg = true;
            }
            if (string.IsNullOrEmpty(dtpDayOfBirth.Text))
            {
                i++;
                if (errflg)
                {
                    strErr.Append("\n");
                }
                strErr.Append(i + ". Chưa nhập ngày sinh.");
                errflg = true;
            }

            if (string.IsNullOrEmpty(txtAdress.Text))
            {
                i++;
                if (errflg)
                {
                    strErr.Append("\n");
                }
                strErr.Append(i + ". Chưa nhập địa chỉ.");
                errflg = true;
            }

            if (!errflg)
            {
                if (id <= 0)
                {
                    string sex = null;
                    sex = rdoMale.Checked ? "M" : "F";
                    int level = 2;
                    DateTime? ngayCap = string.IsNullOrEmpty(txtIdCard.Text) ? default(DateTime?) : dtpIssueDate.Value;
                    //insertKhachThue(string hoTen, DateTime ngaySinh, string gioiTinh, string soDT, string CMND, DateTime ngayCap, string noiCap, string diaChi, string hinhAnh, int soThuePhong)
                    int.TryParse(dao.insertKhachThue(txtFullName.Text, dtpDayOfBirth.Value, sex,
                        txtPhone.Text, txtIdCard.Text,
                        (string.IsNullOrEmpty(txtIdCard.Text) ? default(DateTime?) : dtpIssueDate.Value),
                        (string.IsNullOrEmpty(txtIdCard.Text) ? string.Empty : txtIssuePlace.Text),
                        txtAdress.Text, SqlHelper.readConfigFile("Image Folder"), this.invoiceId, level), out this.id);
                        if( this.id > 0)
                    {
                        if (ptCusImage.Image != null)
                        {
                            ptCusImage.Image.Save(SqlHelper.readConfigFile("Image Folder") + this.id + ".JPG");
                        }
                        Result re = new Result("Lưu thành công.");
                        re.ShowDialog();
                        re.Dispose();
                        loadGrid(this.invoiceId);
                        txtFullName.Text = "";
                        dtpDayOfBirth.Value = DateTime.Now;
                        rdoMale.Checked = true;
                        rdbFemale.Checked = false;
                        txtPhone.Text = "";
                        txtIdCard.Text = "";
                        dtpIssueDate.Value = DateTime.Now;
                        txtIssuePlace.Text = "";
                        txtAdress.Text = "";
                        //ptCusImage.Text = "";
                        ptCusImage.Image = null;
                        this.id = 0;

                    }
                    else
                    {
                        Error err = new Error("Lưu thất bại.");
                        err.ShowDialog();
                        err.Dispose();
                    }
                }
                else
                {
                    string sex = null;
                    DateTime? ngayCap = null;
                    string noiCap = null;
                    sex = rdoMale.Checked ? "M" : "F";

                    if (txtIdCard.Text == null || txtIdCard.Text == "")
                    {
                        ngayCap = default(DateTime?);
                    }
                    else
                    {
                        //ngayCap.Value = dtpIssueDate.Value;
                        ngayCap = dtpIssueDate.Value;
                        noiCap = txtIssuePlace.Text;
                    }
                    //updateKhachThue(int id, string hoTen, DateTime ngaySinh, string gioiTinh, string soDT, string CMND, DateTime ngayCap, string noiCap, string diaChi, string hinhAnh)
                    if (dao.updateKhachThue(this.id, txtFullName.Text, dtpDayOfBirth.Value, sex, txtPhone.Text, txtIdCard.Text,
                        (string.IsNullOrEmpty(txtIdCard.Text) ? default(DateTime?) : dtpIssueDate.Value),
                        (string.IsNullOrEmpty(txtIdCard.Text) ? string.Empty : txtIssuePlace.Text), 
                        txtAdress.Text, SqlHelper.readConfigFile("Image Folder")))
                    {
                        if (ptCusImage.Image != null)
                        {
                            ptCusImage.Image.Save(SqlHelper.readConfigFile("Image Folder") + this.id + ".JPG");
                        }
                        Result re = new Result("Lưu thành công.");
                        re.ShowDialog();
                        re.Dispose();
                        loadGrid(this.invoiceId);                       
                        txtFullName.Text = "";
                        dtpDayOfBirth.Value = DateTime.Now;
                        rdoMale.Checked = true;
                        rdbFemale.Checked = false;
                        txtPhone.Text = "";
                        txtIdCard.Text = "";
                        dtpIssueDate.Value = DateTime.Now;
                        txtIssuePlace.Text = "";
                        txtAdress.Text = "";
                        //ptCusImage.Text = "";
                        ptCusImage.Image = null;
                        this.id = 0;
                    }
                    else
                    {
                        Error err = new Error("Lưu thất bại.");
                        err.ShowDialog();
                        err.Dispose();
                    }
                }
            }
            else
            {
                Error err = new Error(strErr.ToString());
                err.ShowDialog();
                err.Dispose();
            }
        }

        private void btnBrows_Click(object sender, EventArgs e)
        {
            DialogResult result = customerOpenFileDialog.ShowDialog();
            string hinhBenhNhanStr = "";
            if (result != DialogResult.Cancel)
            {
                hinhBenhNhanStr = customerOpenFileDialog.FileName;
                loadImageCapture(hinhBenhNhanStr);
                hinhBenhNhanStr = "";
            }
        }

        private void btnCapture_Click(object sender, EventArgs e)
        {
            Capture f = new Capture();
            f.ShowDialog();
            loadImageCapture(f.Filename);
            f.Dispose();
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            txtFullName.Text = "";
            dtpDayOfBirth.Value = DateTime.Now;
            rdoMale.Checked = true;
            rdbFemale.Checked = false;
            txtPhone.Text = "";
            txtIdCard.Text = "";
            dtpIssueDate.Value = DateTime.Now;
            txtIssuePlace.Text = "";
            txtAdress.Text = "";
            //ptCusImage.Text = "";
            ptCusImage.Image = null;
            this.id = 0;
        }
    }
}
